package org.yufan.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.yufan.bean.User;
import org.yufan.service.UserFrontService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zxd on 2018/4/12.
 */
public class LoginInterceptor implements HandlerInterceptor{
    @Autowired
    private UserFrontService userFrontService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得token
        //1.先从请求参数查找
        String token=request.getParameter("token");
        if(StringUtils.isEmpty(token)){
            //2.如果为空从cookie中找
            Cookie[] cookies = request.getCookies();
            if(cookies!=null){
                //获取token
                for (Cookie c:cookies) {
                    if(c.getName().equals("token")){
                        token=c.getValue();
                    }
                }
            }
        }

        if(StringUtils.isEmpty(token)){
            //如果还还空直接放行
            return true;
        }

        //如果不为空  根据token调用单点登录系统查询
        User user=userFrontService.queryUserByToken(token);

        if(user==null){
            //登录失效，直接放行
            return true;
        }

        //设置用户信息到当前线程
        UserThreadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
